package common;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 处理短信验证码
 * @author 毛建杰
 *
 */
public class SMS
{
	/**
	 * 根据手机号获取短信验证码。1. 从测试服务器下载包含短信验证码的日志到本地；2. 将文件从GBK转换成UTF-8；3. 从文件中提取短信验证码
	 * @param mobile - 手机号
	 * @return 短信验证码，若获取失败返回null
	 * @throws IOException
	 */
	public static String getByMoble(String mobile) throws IOException
	{		
		String fileName = "default" + (new SimpleDateFormat("yyyy-MM-dd")).format(new Date()) +".log.0";
		String localPath = System.getProperty("user.dir") + File.separator + "download" + File.separator + "sms";
		String localFilePath = localPath + File.separator + fileName;
		
		//若目录download/sms不存在，创建目录；若存在，删除当天的sms文件
		File fileTemp = new File(localPath);
		if (fileTemp.exists())
		{
			FileOperation.delete(localFilePath);
		}
		else
		{
			fileTemp.mkdirs();
		}
		
		String remotePath = Config.getValue("SmsSmb-Test", "remotePath") + fileName;
		String remoteAccount = Config.getValue("SmsSmb-Test", "remoteAccount");
		String[] remotePassword = Config.getValue("SmsSmb-Test", "remotePassword").split("\\|");
		
		//配置文件中配置多个密码，如果下载文件失败，尝试更换密码下载
		for (int i=0; i<remotePassword.length; i++)
		{
			if (FileOperation.getSmbFile(remotePath, remoteAccount, remotePassword[i], localPath))
			{
				FileOperation.transferGbkToUtf8(localFilePath, localFilePath);
				break;
			}
		}
		
		String[] lines = FileOperation.read(localFilePath);
		int index = -1;
		for (int i = 0; i < lines.length; i++)
		{
			if (lines[i].equals(" 手机号:" + mobile))
			{
				index = i;
			}
		}
		if (index != -1)
		{
			String smsData = lines[index + 1];
			String sms = smsData.substring(smsData.indexOf("验证码：") + 4, smsData.indexOf("，10分钟内有效"));
			return sms;
		}
		else
		{
			return null;
		}
	}
}
